
<template>
  <el-dialog
    title=" "
    :visible="dialogVisible"
    width="410px"
    :before-close="handleClose"
    @open="changeCode()"
  >
    <div class="content">
      <div class="options">
        <h2
          value="login"
          :class="{ active: option == 'login' }"
          @click="onOptionClick"
        >
          登录
        </h2>
        <h2
          value="register"
          :class="{ active: option == 'register' }"
          @click="onOptionClick"
        >
          注册
        </h2>
      </div>

      <el-form
        class="login-form"
        :model="loginForm"
        :rules="loginFormRules"
        ref="loginForm"
        label-width="0px"
        v-show="option == 'login'"
      >
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user"
            v-model="loginForm.username"
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            prefix-icon="el-icon-key"
            v-model="loginForm.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
          style="width:60%"
            type="text"
            prefix-icon="el-icon-key"
            v-model="loginForm.code"
            placeholder="验证码"
          ></el-input>
          <img class="captcha" @click="changeCode"  :src="codeSrc"/>
        </el-form-item>
        <el-form-item prop="age">
          <el-button
            v-bind:disabled="!isLoginBtnActive"
            class="login-btn"
            type="primary"
            @click="onLogin"
            >登 录</el-button
          >
        </el-form-item>
      </el-form>
      <el-form
        class="register-form"
        status-icon
        :rules="registerRules"
        :model="registerForm"
        @validate="handleRegisterFormValidate"
        ref="registerForm"
        label-width="0px"
        v-show="option == 'register'"
      >
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user"
            v-model="registerForm.username"
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="nickname">
          <el-input
            prefix-icon="el-icon-user"
            v-model="registerForm.nickname"
            placeholder="昵称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            prefix-icon="el-icon-key"
            v-model="registerForm.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
          style="width:60%"
            type="text"
            prefix-icon="el-icon-key"
            v-model="registerForm.code"
            placeholder="验证码"
          ></el-input>
          <img class="captcha" @click="changeCode"  :src="codeSrc"/>
        </el-form-item>
        <el-button
          v-bind:disabled="!isRegisterBtnActive"
          class="login-btn"
          type="primary"
          @click="onRegister"
          >注册</el-button
        >
      </el-form>
    </div>
  </el-dialog>
</template>
<script>
import { mapMutations } from "vuex";
import userApi from "@/axios/userApi";
export default {
    data() {
        var checkUsername = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("用户名不能为空"));
            }
            const reg = new RegExp(/^[a-zA-Z]{1}[a-zA-Z0-9]{3,8}$/);
            if (reg.test(value)) {
                callback();
            }
            else {
                callback(new Error("用户名必须以字母开头，4~9位的的数字字母构成"));
            }
        };
        var checkNickname = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("昵称不能为空"));
            }
            callback();
        };
        var checkPass = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("密码不能为空"));
            }
            if (!/^[^\n\r]{5,20}$/.test(value)) {
                return callback(new Error("密码长度为5到20位字符"));
            }
            return callback();
        };
        return {
            option: "login",
            isRegisterBtnActive: false,
            codeSrc:'/user/code?t=' + Date.now(),
            loginForm: {
                username: "",
                password: "",
                code: "",
            },
            loginFormRules: {
              code: [{ required: true, message: "请输入验证码", trigger: "change" }],
            },
            registerForm: {
                username: "",
                nickname: "",
                password: "",
                code: "",
            },
            registerRules: {
                username: [{ validator: checkUsername, trigger: "blur" }],
                nickname: [{ validator: checkNickname, trigger: "blur" }],
                password: [{ validator: checkPass, trigger: "change" }],
                code: [{ required: true, message: "请输入验证码", trigger: "change" }],
            },
        };
    },
    computed: {
        isLoginBtnActive() {
            return this.loginForm.username && this.loginForm.password && this.loginForm.code;
        },
        dialogVisible: {
            set(v) {
                this.$store.state.isLoginDialog = v;
            },
            get() {
                return this.$store.state.isLoginDialog;
            },
        },
    },
    methods: {
        ...mapMutations("user", ["login", "register"]),
        handleClose(done) {
            this.closeLoginDialog();
        },
        ...mapMutations(["popLoginDialog", "closeLoginDialog"]),
        onOptionClick(e) {
            this.option = e.target.getAttribute("value");
        },
        handleRegisterFormValidate() {
            const stateArr = this.$refs.registerForm.fields.map((c) => c.validateState);
            const isValidated = stateArr.every((s) => s === "success");
            this.isRegisterBtnActive = isValidated;
        },
        onLogin() {
            userApi.login(this.loginForm).then(({ data }) => {
                this.login(data.data);
                this.$refs.loginForm.resetFields();
                this.closeLoginDialog();
            });
        },
        onRegister() {
            let fd = new FormData();
            fd.append("username", this.registerForm.username);
            fd.append("password", this.registerForm.password);
            fd.append("nickname", this.registerForm.nickname);
            fd.append("code",this.registerForm.code)
            userApi.register(fd).then(({ data }) => {
                this.$message.success("注册成功");
                this.$refs.registerForm.resetFields();
                this.option = "login";
            });
        },
      changeCode() {
        this.codeSrc='/user/code?t=' + Date.now()
      }
    },
    mounted() { } 
};
</script>
<style scoped lang="less">
.captcha {
  width: 30%;
  height: 40px;
  margin-left: 10px;
  vertical-align: top;
 
}
.el-dialog {
  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    .options {
      width: 300px;
      display: flex;
      justify-content: space-around;
      h2 {
        cursor: pointer;
        color: var(--text-secondary);
        &.active {
          color: #000;
        }
      }
    }
    .login-form,
    .register-form {
      margin-top: 40px;
      width: 100%;
      .el-form-item {
        margin-bottom: 40px;
      }
      .el-button {
        width: 100% !important;
      }
    }
  }
}
</style>